//
//  WBMainViewController.swift
//  WeiBo
//
//  Created by archermind on 2017/1/13.
//  Copyright © 2017年 Archermind. All rights reserved.
//

import UIKit

/// 主控制器
class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
    }

    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    func composeStatus() {
        
        print("撰写微博")
    }
    
}
// extension 类似于 OC 的分类, 在Swift中还可以用来切分代码块
extension WBMainViewController {
    
    
    func setupComposeButton() {
        
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)

        let w = tabBar.bounds.width / count - CGFloat(1)
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    /// 设置所有子控制器
     func setupChildControllers() {
        
        let array = [["className": "WBHomeViewController", "title": "首页", "imageName": "home"], ["className": "WBMessageViewController", "title": "消息", "imageName": "message_center"], ["className": "UIViewController"],["className": "WBDiscoverViewController", "title": "发现", "imageName": "discover"], ["className": "WBProfileViewController", "title": "我", "imageName": "profile"]]
        
        var arrayM = [UIViewController]()
        
        for dict in array {
            
           arrayM.append(controller(dict: dict))
            
        }
        
        viewControllers = arrayM
        
    }
    
    
    /// 使用一个字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典 [className, title, imageName]
    /// - Returns: 子控制器
    private func controller(dict:[String: String]) -> UIViewController {
        
        guard let className = dict["className"],
                     let title = dict["title"],
                     let imageName = dict["imageName"],
                     let cls = NSClassFromString(Bundle.main.namespace + "." + className) as? UIViewController.Type else {
                            
                            return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        
//        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12)], for: .normal)
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
        
    }

}
